package com.qf.springmvc02.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zed
 * @date 2022/5/5 10:02
 * 自定义的异常解析器,只要控制器中发生异常并抛出了，就会进入到这个类的异常解析方法中
 */
@Component  // 声明组件
public class CustomerExceptionResolver implements HandlerExceptionResolver {

    // 返回的ModelAndView 可以指定显示异常信息的页面 也可以设置异常信息
    // request 请求对象，response响应对象，ex 处理器抛出的异常对象
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 只抛出去自定义的异常对象
        CustomerException exception;
        if(ex instanceof CustomerException){
            exception = (CustomerException)ex;
        }else {
            exception = new CustomerException(ex.getMessage());
        }

        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("error",exception.getMessage());
        return modelAndView;
    }
}
